<template>
  <div style="border: 1px solid #dcdfe6">
    <Toolbar
      style="border-bottom: 1px solid #dcdfe6"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      :style="`height: ${height}; overflow-y: hidden`"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import { http } from 'jax-node'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const emits = defineEmits(['update:modelValue'])
const props = defineProps({
  uploadUrl: { type: String, default: '/upload?bucket=wang-editor' },
  modelValue: String,
  height: { type: String, default: '320px' }
})

const valueHtml = computed({
  get: () => props.modelValue,
  set: val => emits('update:modelValue', val == '<p><br></p>' ? '' : val),
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const upload = file => {
  var formData = new FormData()
  formData.append('files', file)

  return http({
    url: props.uploadUrl,
    method: 'POST',
    data: formData,
  })
}

const toolbarConfig = {
  excludeKeys: ['fullScreen', 'group-video']
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: props.uploadUrl,
      fieldName: 'files',
      customUpload(file, insertFn) {
        console.log('customUpload')

        upload(file).then(res => {
          insertFn(res[0].url)
        })
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 记录 editor 实例，重要！
const handleCreated = editor => (editorRef.value = editor)
</script>
